package com.lagou.zk;

import org.I0Itec.zkclient.ZkClient;
import org.junit.Test;

import java.io.*;

/**
 * @Author Cao Dun
 * @Date 2021/3/23 20:23
 * @Version 1.0
 * @Description 发布数据库连接池信息到ZK集群
 */
public class PutGetCfg {

    //zk集群连接信息
    public static final String ZK_CLUSTER="linux121:2181,linux122:2181,linux123:2181";
    //web的数据库连接池在zk集群的存放目录
    public static final String POOL_PATH="/webapp/dblinkcfg";
    //ZkClient
    private ZkClient zkClient = null;

    //获取zk的连接
    public ZkClient getZkClient() {
        if (zkClient == null) {
            createZk();
        }
        return zkClient;
    }

    /**
     * 创建zk客户端，并且在zk集群创建db连接池共享目录
     */
    public void createZk(){
        zkClient = new ZkClient(ZK_CLUSTER);
        //创建webapp目录
        if(!zkClient.exists("/webapp")){
            zkClient.createPersistent("/webapp");
        }
        if(!zkClient.exists(POOL_PATH)){
            zkClient.createPersistent(POOL_PATH);
        }
    }


    /**
     * 发布数据库配置信息
     */
    public void putCfg(String cfgFile) throws IOException {
        InputStream inputStream = PutGetCfg.class.getClassLoader().getResourceAsStream(cfgFile);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String cfgInfo="";
        while(true){
            String s = reader.readLine();
            if( s == null){
                break;
            }else{
                System.out.println(s);
                cfgInfo += " " + s;
            }
        }
        //zkClient = new ZkClient(ZK_CLUSTER);
        zkClient.writeData(POOL_PATH, cfgInfo);

    }

    /**
     * 获取zk集群上的配置文件信息并回写到druid.properties文件中
     * @throws IOException
     */
    @Test
    public void getCfg() throws IOException {
        String str = (String)zkClient.readData(POOL_PATH);
        String cfgInfo = str.replaceAll(" ", "\n");
        System.out.println("新的连接池信息");
        System.out.println(cfgInfo);

        //把数据回写到druid.properties文件中
        BufferedWriter writer = new BufferedWriter(new FileWriter("src/main/resources/druid.properties"));
        writer.write(cfgInfo);
        writer.flush();
        writer.close();
    }
}
